package com.huatai.saas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.*;
import com.huatai.model.dubbo.ModelDubboApi;
import com.huatai.model.entity.Model;
import com.huatai.model.entity.ModelQuery;
import com.huatai.saas.entity.UserModelAuth;
import com.huatai.saas.mapper.UserModelAuthMapper;
import com.huatai.saas.service.FileService;
import com.huatai.saas.service.UserModelAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.saas.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * <p>
 * 用户模型授权表 服务实现类
 * </p>
 *
 * @author songxiude
 * @since 2024-04-28
 */
@Service
public class UserModelAuthServiceImpl extends ServiceImpl<UserModelAuthMapper, UserModelAuth> implements UserModelAuthService {

	@DubboReference(check = false)
	private ModelDubboApi modelDubboApi;

	@Autowired
	private FileService fileService;

	/**
	 * 用户模型授权
	 *
	 * @param authParamVo
	 * @return
	 */
	public boolean userModelAuth(ModelAuthParamVo authParamVo) {
		Long createUid = AuthUtil.getUser().getUserId();
		List<UserModelAuth> userModelAuths = new ArrayList<>();
		if (CollectionUtil.isEmpty(authParamVo.getModels())) {
			throw new ServiceException("授权模型不能为空");
		}
		//组装模型ID
		for (ModelEntityVo modelEntityVo : authParamVo.getModels()) {
			LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
			wrapper.eq(UserModelAuth::getUserId, authParamVo.getUserId());
			wrapper.eq(UserModelAuth::getModelId, modelEntityVo.getModelId());
			wrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
			//判断是否未授权
			if (ObjectUtil.isNotEmpty(getOne(wrapper))) {
				continue;
			}
			UserModelAuth userModelAuth = new UserModelAuth();
			userModelAuth.setAuthUserId(createUid);
			userModelAuth.setUserId(authParamVo.getUserId());
			userModelAuth.setModelId(modelEntityVo.getModelId());
			userModelAuth.setModelName(modelEntityVo.getModelName());
			userModelAuth.setIndustryKey(modelEntityVo.getIndustryKey());
			userModelAuth.setRemark(authParamVo.getRemark());
			userModelAuth.setAuthStartTime(authParamVo.getAuthStartTime());
			userModelAuth.setAuthEndTime(authParamVo.getAuthEndTime());
			userModelAuths.add(userModelAuth);
		}
		return saveBatch(userModelAuths);
	}

	/**
	 * 用户获取模型列表
	 *
	 * @param paramVo
	 * @return
	 */
	public IPage<ModelVo> getUserModels(UserModelParamVo paramVo) {
		Page<ModelVo> page = PaginationUtils.getPage(paramVo.getPage(), paramVo.getSize());
		LambdaQueryWrapper<UserModelAuth> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(UserModelAuth::getUserId, AuthUtil.getUser().getUserId());
		//限制只查有效期范围的
//		queryWrapper.between()
		queryWrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
		queryWrapper.like(StringUtil.isNotBlank(paramVo.getModelName()), UserModelAuth::getModelName, paramVo.getModelName());
		queryWrapper.eq(StringUtil.isNotBlank(paramVo.getIndustryKey()),UserModelAuth::getIndustryKey,paramVo.getIndustryKey());
		queryWrapper.orderByDesc(UserModelAuth::getCreateTime);
		IPage<ModelVo> models = baseMapper.getUserModels(page, queryWrapper);
		//远程调用补全缩略图
		models.getRecords().forEach(modelVo -> {
			Model model = modelDubboApi.getModelById(modelVo.getModelId());
			modelVo.setSimpleMap(model.getSimpleMap());
			modelVo.setIndustryKey(model.getIndustryKey());
			modelVo.setDiffuseMap(model.getDiffuseMap());
			modelVo.setMirrorMap(model.getMirrorMap());
			modelVo.setNormalMap(model.getNormalMap());
			modelVo.setRemark(model.getRemark());
			modelVo.setFbxFileType(model.getFbxFileType());
			modelVo.setPrice(model.getPrice());
			modelVo.setIndustryKeyName(model.getIndustryKeyName());
		});
		return models;
	}

	/**
	 * 模型文件分片下载
	 * @param modelId
	 * @param shardingNum
	 */
	public void modelDownload(Long modelId, int shardingNum) {
		LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(UserModelAuth::getUserId,AuthUtil.getUser().getUserId());
		wrapper.eq(UserModelAuth::getModelId,modelId);
		wrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
		UserModelAuth modelAuth = getOne(wrapper);
		if(ObjectUtil.isEmpty(modelAuth)){
			throw new ServiceException("该模型未授权");
		}
		Model model = modelDubboApi.getModelById(modelId);

		//fileService.download(model.getFbxFile(),shardingNum);
		fileService.download(model.getZipFile(),shardingNum);
	}

	/**
	 * 获取文件分片数
	 * @param modelId
	 * @return
	 */
	public int getFileShardingNumber(Long modelId) {
		LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(UserModelAuth::getUserId,AuthUtil.getUser().getUserId());
		wrapper.eq(UserModelAuth::getModelId,modelId);
		wrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
		UserModelAuth modelAuth = getOne(wrapper);
		if(ObjectUtil.isEmpty(modelAuth)){
			throw new ServiceException("该模型未授权");
		}
		Model model = modelDubboApi.getModelById(modelId);
		//int partNums = fileService.getFilePartNums(model.getFbxFile());
		int partNums = fileService.getFilePartNums(model.getZipFile());
		return partNums;
	}

	/**
	 * 模型独立下载
	 * @param modelId
	 */
	public void oneModelDownload(Long modelId) {
		LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(UserModelAuth::getUserId,AuthUtil.getUser().getUserId());
		wrapper.eq(UserModelAuth::getModelId,modelId);
		wrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
		UserModelAuth modelAuth = getOne(wrapper);
		if(ObjectUtil.isEmpty(modelAuth)){
			throw new ServiceException("该模型未授权");
		}
		Model model = modelDubboApi.getModelById(modelId);

		//fileService.download(model.getFbxFile());
		fileService.download(model.getZipFile());
	}

	/**
	 * 获取用户端模型列表
	 * @param paramVo
	 * @return
	 */
	public IPage<ModelVo> getUserModelList(UserModelParamVo paramVo) {
		Page<ModelVo> page = PaginationUtils.getPage(paramVo.getPage(), paramVo.getSize());
		LambdaQueryWrapper<UserModelAuth> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(UserModelAuth::getUserId, paramVo.getUserId());
		//限制只查有效期范围的
//		queryWrapper.between()
		queryWrapper.ge(UserModelAuth::getAuthEndTime, LocalDateTime.now());
		queryWrapper.like(StringUtil.isNotBlank(paramVo.getModelName()), UserModelAuth::getModelName, paramVo.getModelName());
		queryWrapper.orderByDesc(UserModelAuth::getCreateTime);
		IPage<ModelVo> models = baseMapper.getUserModels(page, queryWrapper);
		//远程调用补全缩略图
		models.getRecords().forEach(modelVo -> {
			Model model = modelDubboApi.getModelById(modelVo.getModelId());
			modelVo.setSimpleMap(model.getSimpleMap());
			modelVo.setIndustryKeyName(model.getIndustryKeyName());
			modelVo.setPrice(model.getPrice());
			modelVo.setModelType(model.getModelType());
		});
		return models;
	}

	/**
	 * 批量删除用户授权模型
	 * @param models
	 * @return
	 */
	public boolean delUserModels(DelModelParamVo models) {
		if(CollectionUtil.isEmpty(models.getAuthIds())){
			throw new ServiceException("模型列表不能为空");
		}
		LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(UserModelAuth::getUserId,models.getUserId());
		wrapper.in(UserModelAuth::getId,models.getAuthIds());
		return remove(wrapper);
	}

	/**
	 * 获取模型列表（回显）
	 * @param modelQuery
	 * @return
	 */
	public IPage<Model> getModelList(ModelQuery modelQuery) {
		IPage<Model> modelPage = modelDubboApi.modelPage(modelQuery);
//		Long userId = AuthUtil.getUser().getUserId();
		LocalDateTime now = LocalDateTime.now();
//		if(CollectionUtil.isNotEmpty(modelPage.getRecords())){
//			modelPage.getRecords().forEach(model -> {
//				UserModelAuth modelAuth = getUserModelAuth(model.getId(), modelQuery.getUserId(), now);
//				if(ObjectUtil.isNotEmpty(modelAuth) && modelQuery.getIsShow()==1){
//					modelPage.getRecords().remove(model);
//				}else if (ObjectUtil.isNotEmpty(modelAuth) && modelQuery.getIsShow()==0) {
//					model.setSelectStatus(true);
//				}
//			});
//		}
		if(CollectionUtil.isNotEmpty(modelPage.getRecords())){
			Iterator<Model> iterator = modelPage.getRecords().iterator();
			while (iterator.hasNext()){
				Model model = iterator.next();
				UserModelAuth modelAuth = getUserModelAuth(model.getId(), modelQuery.getUserId(), now);
				//如果设置过滤删除元素
				if(ObjectUtil.isNotEmpty(modelAuth) && modelQuery.getIsShow()==1){
					iterator.remove();
				} else if (ObjectUtil.isNotEmpty(modelAuth) && modelQuery.getIsShow()==0) {
					model.setSelectStatus(true);
				}
			}
		}

		return modelPage;
	}

	/**
	 * 获取模型授权详细信息
	 * @param modelId
	 * @return
	 */
	public UserModelAuth getUserModelAuth(Long modelId,Long userId,LocalDateTime now){
		LambdaQueryWrapper<UserModelAuth> wrapper = Wrappers.lambdaQuery();
		wrapper.ge(UserModelAuth::getAuthEndTime, now);
		wrapper.eq(UserModelAuth::getUserId,userId);
		wrapper.eq(UserModelAuth::getModelId,modelId);

		return getOne(wrapper);
	}

}
